<template>
	<div>
		<Select
			v-model="innerValue"
			:placeholder="placeholder"
			:clearable="clearable"
			:multiple="multiple"
			:disabled="disabled"
			:filterable="filterable"
			:collapse-tags="collapseTags"
			:allow-create="allowCreate"
			@change="onChange()"
		>
			<Option
				v-for="item in innerOptions"
				:key="item[props.value]"
				:label="item[props.label]"
				:value="item[props.value]"
				:disabled="item.disabled"
			>
				<slot
					name="default"
					v-bind="item"
				/>
			</Option>
		</Select>
	</div>
</template>
<script>
import {Select,Option } from 'element-ui'
const dataCache = {};
import {magic} from '@lexmis/magic-ui/pc';
export default {
	name:'McSelect',
	components:{
		Select,
		Option
	},
	props:{
		value:{
			type:[String, Array],
			default:null,
		},
		options:{
			type:Array,
			default: () => [],
		},
		relationField:{
			type:String,
			default:'',
		},
		placeholder:{
			type:String,
			default:'请选择',
		},
		disabled:{
			type:Boolean,
			default:false,
		},
		multiple:{
			type:Boolean,
			default:false,
		},
		collapseTags:{
			type:Boolean,
			default:false,
		},
		filterable:{
			type:Boolean,
			default:false,
		},
		clearable:{
			type:Boolean,
			default:true,
		},
		allowCreate:{
			type:Boolean,
			default:false,
		},
		props:{
			type:Object,
			default: () => ({value:'id', label:'fullName'}),
		},
		config:{
			type:Object,
			default: () => ({
				dataType:'static',
			}),
		},
	},
	data(){
		return {
			innerValue:'',
			innerOptions:[],
		};
	},
	watch:{
		value(newVal){
			this.innerValue = newVal;
		},
		options(val){
			this.innerOptions = val;
		},
	},
	created(){
		this.getOptions();
	},
	methods:{
		onChange(){
			this.$emit('input', this.innerValue);
			this.$emit('change', this.innerValue);
		},
		getOptions(){
			const {dataType, dataTypeId} = this.config;
			const cacheKey = `${dataType}_${dataTypeId}`;

			// 定义不同数据类型的缓存时间
			const cacheDurations = {
				enums:1 * 60 * 1000, // 1 分钟
				dictionary:1 * 60 * 1000, // 1 分钟
				dynamic:1 * 60 * 1000, // 1 分钟
				form:10 * 1000, // 10 秒
			};

			const cacheDuration = cacheDurations[dataType];
			const shouldCache = cacheDuration !== undefined;

			// 检查缓存数据是否存在且未过期
			if(shouldCache && dataCache[cacheKey] && (Date.now() - dataCache[cacheKey].timestamp < cacheDuration)){
				this.innerOptions = dataCache[cacheKey].options;
				return;
			}

			// 请求配置
			let requestConfig = null;
			switch(dataType){
				case 'enums':
					requestConfig = {url:'/api/enums', method:'get'};
					break;
				case 'form':
					requestConfig = {
						url:'/api/form/instance/list-select',
						method:'post',
						data:{
							templateId:dataTypeId,
							columnOptions:[this.relationField],
							currentPage:1,
							pageSize:1000,
						},
					};
					break;
				case 'dictionary':
					requestConfig = {url:`/api/system/DictionaryData/${dataTypeId}/Data/Selector`, method:'get'};
					break;
				case 'dynamic':
					requestConfig = {url:`/api/system/DataInterface/${dataTypeId}/Actions/Preview`, method:'post'};
					break;
				default:
					this.innerOptions = this.options;
					return;
			}

			magic.core.service(requestConfig)
					.then(({data}) => {
						let options;
						switch(dataType){
							case 'enums': {
								if(dataTypeId && dataTypeId.indexOf('.') > -1){
									options = data[dataTypeId].map((item) => ({
										id:item.code,
										fullName:item.localizedMessage,
									}));
								}else{
									const enums = Object.keys(data).reduce((newEnums, key) => {
										const trimmedKey = key.substring(key.lastIndexOf('.') + 1);
										newEnums[trimmedKey] = data[key];
										return newEnums;
									}, {});
									options = enums[dataTypeId].map((item) => ({
										id:item.code,
										fullName:item.localizedMessage,
									}));
								}
								break;
							}
							case 'form':
								options = data.list.map((item) => ({
									fullName:item[this.relationField],
									id:item.id,
								}));
								break;
							case 'dictionary':
								options = data.list;
								break;
							case 'dynamic':
								options = data.map((item) => ({
									id:item.id,
									fullName:item.name,
								}));
								break;
						}

						// 更新组件数据并缓存结果
						this.innerOptions = options;
						if(shouldCache){
							dataCache[cacheKey] = {options, timestamp:Date.now()};
						}
					})
					.catch((error) => {
						console.error(`未能获取数据类型选项 ${dataType}:`, error);
						this.innerOptions = [];
					});
		},

	},
};
</script>